//
//  LauTitleButton.swift
//  SwiftProject
//
//  Created by Lausen on 2017/8/17.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit

class LauTitleButton: UIButton {

    /// 重载构造函数
    ///
    /// - Parameter title: 传入的按钮的title
    init(title: String?) {
        super.init(frame: CGRect()) //调用一下父类的默认构造方法
        
        //1:设置title
        if title == nil {
            
            setTitle("首页", for: .normal)
            
        }else{
            
            setTitle(title! + " ", for: .normal)
            
            //设置图片
            setImage(UIImage(named: "navigationbar_arrow_down"), for: .normal)
            setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        }
        
        //2:设置字体大小和字体颜色
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        setTitleColor(UIColor.darkGray, for: [])
        setTitleColor(UIColor.black, for: .selected)
        
        //3:设置大小
        sizeToFit()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews() //使用布局的方法,一定要调用父类的方法,要不然会出错的额
        
        //先判断是不是有titleLable和imageView
        guard let titleLabel = titleLabel,
            let imageView = imageView
        else {
            
            //如果titleLable和imageView任何一个没有,就直接返回
            return
        }
        
        //将titleLabel向左移动imageView的宽度个像素
        titleLabel.frame = CGRect(x: 0, y: 0, width: titleLabel.bounds.width, height: titleLabel.bounds.height)
        //将imageView向右移动titlelabel的宽度个像素
        imageView.frame = CGRect(x: titleLabel.bounds.width, y: (bounds.height - imageView.bounds.height) * 0.5, width: imageView.bounds.width, height: imageView.bounds.height)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
